package com.headwind.multi.datasource.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * @author : Headwind
 * @version : 1.0
 * @date : Created in 2020/8/13
 * @description : 数据源配置类
 */
@Log4j2
@Configuration
public class DataSourceConfig {

    /**
     * 主数据源
     */
    public final static String MASTER_DATASOURCE = "masterDataSource";
    /**
     * 读数据源
     */
    public final static String READ_DATASOURCE = "readDataSource";

    /**
     * 读数据源 Bean 配置
     *
     * @return 数据源配置 Bean
     */
    @Bean(value = READ_DATASOURCE)
    @Qualifier(READ_DATASOURCE)
    @ConfigurationProperties("spring.datasource.druid.read")
    public DataSource readDataSource() {
        log.info("Read Datasource created");
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 主数据源 Bean 配置
     *
     * @return 数据源配置 Bean
     */
    @Primary
    @Bean(value = MASTER_DATASOURCE)
    @Qualifier(MASTER_DATASOURCE)
    @ConfigurationProperties("spring.datasource.druid.master")
    public DataSource masterDataSource() {
        log.info("Master Datasource created");
        return DruidDataSourceBuilder.create().build();
    }
}
